<template>
  <Dialog
    :title="t('stageDebateTime.form.title')"
    v-model="dialogVisible"
    width="570"
    :fullscreen="false"
  >
    <div v-loading="formLoading">
      <el-form ref="formRef2" :model="rulesInfo" :rules="formRules" label-width="120px">
        <el-form-item :label="t('stageDebateTime.form.date')" prop="debateTime">
          <el-date-picker
            v-model="rulesInfo.debateTime"
            :placeholder="t('common.selectTextPlaceholder') + t('stageDebateTime.form.date')"
            type="date"
            value-format="x"
          />
        </el-form-item>
      </el-form>
      <el-form
        ref="formRef"
        :model="formData"
        :rules="formRules"
        label-width="120px"
        :disabled="!rulesInfo.debateTime"
      >
        <el-form-item :label="t('stageDebateTime.fields.gap')" prop="gap">
          <el-input-number
            style="width: 100%"
            v-model="formData.gap"
            :min="0"
            :placeholder="t('common.inputTextPlaceholder') + t('stageDebateTime.fields.gap')"
          />
        </el-form-item>
        <el-form-item :label="t('stageDebateTime.fields.debateStartTime')" prop="debateStartTime">
          <el-time-picker
            style="width: 100%"
            v-model="startTime"
            :placeholder="
              t('common.selectTextPlaceholder') + t('stageDebateTime.fields.debateStartTime')
            "
            value-format="HH:mm:ss"
          />
        </el-form-item>

        <el-form-item :label="t('stageDebateTime.fields.breakTime')" prop="breakTime">
          <div class="w-1/1 mb-[5px]" v-for="(_, index) in breakTimeArray" :key="index">
            <el-time-picker
              v-model="breakTimeArray[index]"
              is-range
              value-format="HH:mm:ss"
              :start-placeholder="
                t('common.selectTextPlaceholder') + t('stageDebateTime.fields.breakTime')
              "
              :end-placeholder="
                t('common.selectTextPlaceholder') + t('stageDebateTime.fields.breakTime')
              "
            />
            <el-button
              type="danger"
              plain
              size="small"
              :icon="Close as any"
              circle
              class="ml-[10px]"
              :disabled="breakTimeArray.length <= 1"
              @click="handleRemoveBreakTime(index)"
            />
          </div>
          <el-button type="primary" plain @click="breakTimeArray.push([])">
            {{ t('stageDebateTime.form.addBreakTime') }}
          </el-button>
        </el-form-item>

        <el-form-item :label="t('stageDebateTime.fields.priority')" prop="priority">
          <el-radio-group v-model="formData.priority">
            <el-radio value="博士优先">{{ t('stageDebateTime.form.phdFirst') }}</el-radio>
            <el-radio value="硕士优先">{{ t('stageDebateTime.form.masterFirst') }}</el-radio>
          </el-radio-group>
        </el-form-item>
      </el-form>
    </div>
    <template #footer>
      <el-button @click="submitForm" type="primary" :disabled="formLoading"
        >{{ t('common.ok') }}
      </el-button>
      <el-button @click="dialogVisible = false">{{ t('common.cancel') }}</el-button>
    </template>
  </Dialog>
</template>
<script setup lang="ts">
import { StageDebateTimeApi, StageDebateTimeVO } from '@/api/awards/stagedebatetime'
import { FormRules } from 'element-plus'
import { InstanceRuleApi, InstanceRuleVO } from '@/api/awards/instancerule'
import { formatDate } from '@/utils/formatTime'
import { Close } from '@element-plus/icons-vue'
import _ from 'lodash-es'

/** 阶段-答辩时间安排 表单 */
defineOptions({ name: 'StageDebateTimeForm' })

const { t } = useI18n() // 国际化
const message = useMessage() // 消息弹窗

const dialogVisible = ref(false) // 弹窗的是否展示
const dialogTitle = ref('') // 弹窗的标题
const formLoading = ref(false) // 表单的加载中：1）修改时的数据加载；2）提交的按钮禁用
const formType = ref('') // 表单的类型：create - 新增；update - 修改
const formData = ref({
  id: undefined,
  instanceRuleId: undefined,
  awardsId: undefined,
  breakTime: undefined,
  gap: undefined,
  debateStartTime: undefined,
  priority: undefined,
  remark: undefined
})
const formRules = reactive<FormRules>({
  debateTime: [
    {
      required: true,
      message: t('common.selectTextPlaceholder') + t('stageDebateTime.form.date'),
      trigger: 'blur'
    }
  ],
  instanceRuleId: [
    {
      required: true,
      message: t('common.inputTextPlaceholder') + t('stageDebateTime.fields.instanceRuleId'),
      trigger: 'blur'
    }
  ],
  awardsId: [
    {
      required: true,
      message: t('common.inputTextPlaceholder') + t('stageDebateTime.fields.awardsId'),
      trigger: 'blur'
    }
  ],
  breakTime: [
    {
      required: true,
      message: t('common.inputTextPlaceholder') + t('stageDebateTime.fields.breakTime'),
      trigger: 'blur'
    }
  ],
  gap: [
    {
      required: true,
      message: t('common.inputTextPlaceholder') + t('stageDebateTime.fields.gap'),
      trigger: 'blur'
    }
  ],
  debateStartTime: [
    {
      required: true,
      message: t('common.selectTextPlaceholder') + t('stageDebateTime.fields.debateStartTime'),
      trigger: 'change'
    }
  ],
  priority: [
    {
      required: true,
      message: t('common.selectTextPlaceholder') + t('stageDebateTime.fields.priority'),
      trigger: 'change'
    }
  ]
})
const formRef = ref() // 表单 Ref
const formRef2 = ref() // 表单 Ref

const startTime = computed({
  get: () => {
    return formatDate(formData.value.debateStartTime, 'HH:mm:ss')
  },
  set: (val: string) => {
    let date
    if (rulesInfo.value?.debateTime) {
      date = formatDate(rulesInfo.value.debateTime, 'YYYY-MM-DD')
    } else {
      date = formatDate(new Date(), 'YYYY-MM-DD')
    }
    formData.value.debateStartTime = new Date(date + ' ' + val).getTime() as any
  }
})

const breakTimeArray = ref<string[][]>([[]])

watchEffect(() => {
  formData.value.breakTime = JSON.stringify(breakTimeArray.value) as any
})

const awardsId = ref('')
const rulesInfo = ref<InstanceRuleVO>({} as InstanceRuleVO)

/**
 * 打开弹窗
 *
 * @param _awardsId 评奖ID
 * @param _rule     当前阶段的规则
 */
const open = async (_awardsId: string, _rule: InstanceRuleVO) => {
  awardsId.value = _awardsId
  rulesInfo.value = _.cloneDeep(_rule)
  dialogVisible.value = true
  resetForm()
  formLoading.value = true
  try {
    // 根据ruleId查询
    const data = await StageDebateTimeApi.getStageDebateTimeByRuleId(rulesInfo.value.id)

    if (data) {
      // 修改
      formType.value = 'update'
      formData.value = data
      breakTimeArray.value = JSON.parse(data.breakTime ?? [[]])
    } else {
      // 新增
      formType.value = 'create'
    }
    formData.value.awardsId = awardsId.value as any
    formData.value.instanceRuleId = rulesInfo.value.id as any
  } finally {
    formLoading.value = false
  }
}
defineExpose({ open }) // 提供 open 方法，用于打开弹窗

/** 提交表单 */
const emit = defineEmits(['success']) // 定义 success 事件，用于操作成功后的回调
const submitForm = async () => {
  try {
    // 校验表单
    await Promise.all([formRef.value.validate(), formRef2.value.validate()])
  } catch {
    return
  }
  // 提交请求
  formLoading.value = true
  try {
    formData.value.debateStartTime = new Date(
      formatDate(rulesInfo.value.debateTime, 'YYYY-MM-DD') +
        ' ' +
        formatDate(formData.value.debateStartTime, 'HH:mm:ss')
    ).getTime() as any
    const data = formData.value as unknown as StageDebateTimeVO
    await InstanceRuleApi.updateInstanceRule(rulesInfo.value)
    if (formType.value === 'create') {
      await StageDebateTimeApi.createStageDebateTime(data)
      message.success(t('common.createSuccess'))
    } else {
      await StageDebateTimeApi.updateStageDebateTime(data)
      message.success(t('common.updateSuccess'))
    }
    dialogVisible.value = false
    // 发送操作成功的事件
    emit('success')
  } finally {
    formLoading.value = false
  }
}

/** 重置表单 */
const resetForm = () => {
  formData.value = {
    id: undefined,
    instanceRuleId: undefined,
    awardsId: undefined,
    breakTime: undefined,
    gap: undefined,
    debateStartTime: undefined,
    priority: undefined,
    remark: undefined
  }
  formRef.value?.resetFields()
  formRef2.value?.resetFields()
}

const handleRemoveBreakTime = (index: number) => {
  breakTimeArray.value.splice(index, 1)
}
</script>
